#include "axp202.h"
#include "board.h"
#include "display.h"

#include <esp_log.h>

#define TAG "Axp202"

Axp202::Axp202(i2c_master_bus_handle_t i2c_bus, uint8_t addr) : I2cDevice(i2c_bus, addr) {
}

int Axp202::GetBatteryCurrentDirection() {
    uint8_t reg = ReadReg(0x00);
    return (reg & 0x04) ? 1 : -1;
}

bool Axp202::IsCharging() {
    uint8_t reg = ReadReg(0x01);
    return reg & 0x40;
}

bool Axp202::IsDischarging() {
    uint8_t reg = ReadReg(0x00);
    return !(reg & 0x04);  // Bit 2 == 0 表示正在放电
}

bool Axp202::IsChargingDone() {
    uint8_t irq = ReadReg(0x49);
    return irq & 0x04;  // Bit 2
}

int Axp202::GetBatteryLevel() {
    uint8_t high = ReadReg(0x78);
    uint8_t low = ReadReg(0x79) & 0x0F;
    uint16_t raw = (high << 4) | low;
    float voltage = raw * 1.1f;  // mV

    // 假设 3.3V = 0%，4.2V = 100%
    if (voltage < 3300) return 0;
    if (voltage > 4200) return 100;
    return (int)((voltage - 3300) * 100 / (4200 - 3300));
}

void Axp202::PowerOff() {
    WriteReg(0x32, 0x80);
}
